<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${title}">MCP Client 管理界面</title>
    <!-- Ant Design CSS -->
    <link href="https://cdn.jsdelivr.net/npm/antd@5.12.8/dist/reset.css" rel="stylesheet">
    <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/antd@5.12.8/dist/antd.min.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
            background-color: #f0f2f5;
        }
        .admin-container {
            min-height: 100vh;
        }
        .header-bar {
            background: linear-gradient(135deg, #1890ff 0%, #722ed1 100%);
            color: white;
            padding: 16px 24px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .content-area {
            padding: 24px;
        }
        .status-card {
            margin-bottom: 24px;
        }
        .action-buttons {
            margin-bottom: 24px;
        }
        .data-table {
            background: white;
            border-radius: 8px;
            padding: 24px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .json-editor {
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        }
        .status-indicator {
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #ff4d4f;
        }
        .status-dot.connected {
            background-color: #52c41a;
        }
        .tool-card {
            margin-bottom: 16px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .tool-card:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        .resource-item {
            padding: 12px;
            border: 1px solid #f0f0f0;
            border-radius: 6px;
            margin-bottom: 8px;
            background: #fafafa;
        }
    </style>
</head>
<body>
    <div id="root"></div>

    <script type="text/babel">
        const { useState, useEffect } = React;
        const { 
            Layout, Card, Button, Input, Select, Form, Space, Typography, 
            Divider, Badge, Tag, Alert, Tabs, Row, Col, Spin, message,
            Modal, Table, Descriptions, Statistic
        } = antd;
        const { Header, Content } = Layout;
        const { Title, Text, Paragraph } = Typography;
        const { TextArea } = Input;
        const { TabPane } = Tabs;

        const McpAdminPanel = () => {
            const [connectionStatus, setConnectionStatus] = useState(false);
            const [loading, setLoading] = useState(false);
            const [tools, setTools] = useState([]);
            const [resources, setResources] = useState([]);
            const [serverConfig, setServerConfig] = useState({
                serverUri: 'ws://localhost:8080/mcp',
                type: 'neo4j',
                config: {
                    uri: 'bolt://localhost:7687',
                    username: 'neo4j',
                    password: 'password'
                }
            });
            const [statistics, setStatistics] = useState({
                totalTools: 0,
                totalResources: 0,
                successfulCalls: 0,
                failedCalls: 0
            });

            const API_BASE = '/api/mcp';

            useEffect(() => {
                checkConnectionStatus();
                loadStatistics();
            }, []);

            const checkConnectionStatus = async () => {
                try {
                    const response = await axios.get(`${API_BASE}/status`);
                    setConnectionStatus(response.data.connected);
                    if (response.data.connected) {
                        await loadTools();
                        await loadResources();
                    }
                } catch (error) {
                    console.error('检查连接状态失败:', error);
                }
            };

            const loadStatistics = () => {
                // 模拟统计数据
                setStatistics({
                    totalTools: tools.length,
                    totalResources: resources.length,
                    successfulCalls: Math.floor(Math.random() * 100),
                    failedCalls: Math.floor(Math.random() * 10)
                });
            };

            const handleConnect = async () => {
                setLoading(true);
                try {
                    const response = await axios.post(`${API_BASE}/connect`, {
                        serverUri: serverConfig.serverUri
                    });
                    
                    if (response.status === 200) {
                        setConnectionStatus(true);
                        message.success('连接成功');
                        await handleInitialize();
                        await loadTools();
                        await loadResources();
                    }
                } catch (error) {
                    message.error('连接失败: ' + (error.response?.data || error.message));
                } finally {
                    setLoading(false);
                }
            };

            const handleDisconnect = async () => {
                setLoading(true);
                try {
                    await axios.post(`${API_BASE}/disconnect`);
                    setConnectionStatus(false);
                    setTools([]);
                    setResources([]);
                    message.success('断开连接成功');
                } catch (error) {
                    message.error('断开连接失败: ' + (error.response?.data || error.message));
                } finally {
                    setLoading(false);
                }
            };

            const handleInitialize = async () => {
                try {
                    const clientInfo = {
                        name: 'MCP Web Admin',
                        version: '1.0.0',
                        config: serverConfig.config
                    };
                    
                    await axios.post(`${API_BASE}/initialize`, clientInfo);
                    message.success('初始化成功');
                } catch (error) {
                    message.error('初始化失败: ' + (error.response?.data || error.message));
                }
            };

            const loadTools = async () => {
                try {
                    const response = await axios.get(`${API_BASE}/tools`);
                    setTools(response.data || []);
                } catch (error) {
                    console.error('加载工具失败:', error);
                }
            };

            const loadResources = async () => {
                try {
                    const response = await axios.get(`${API_BASE}/resources`);
                    setResources(response.data || []);
                } catch (error) {
                    console.error('加载资源失败:', error);
                }
            };

            const handleCallTool = async (toolName, params) => {
                setLoading(true);
                try {
                    const parsedParams = typeof params === 'string' ? JSON.parse(params) : params;
                    const response = await axios.post(`${API_BASE}/tools/${toolName}/call`, parsedParams);
                    
                    Modal.info({
                        title: `工具执行结果: ${toolName}`,
                        content: (
                            <pre style={{ maxHeight: '400px', overflow: 'auto' }}>
                                {JSON.stringify(response.data, null, 2)}
                            </pre>
                        ),
                        width: 800
                    });
                    message.success('工具执行成功');
                } catch (error) {
                    message.error('工具执行失败: ' + (error.response?.data || error.message));
                } finally {
                    setLoading(false);
                }
            };

            const toolColumns = [
                {
                    title: '工具名称',
                    dataIndex: 'name',
                    key: 'name',
                    render: (text) => <Text strong>{text}</Text>
                },
                {
                    title: '描述',
                    dataIndex: 'description',
                    key: 'description',
                    render: (text) => text || '无描述'
                },
                {
                    title: '操作',
                    key: 'action',
                    render: (_, record) => (
                        <Button 
                            type="primary" 
                            size="small"
                            onClick={() => {
                                Modal.confirm({
                                    title: `调用工具: ${record.name}`,
                                    content: (
                                        <div>
                                            <p>{record.description}</p>
                                            <TextArea 
                                                id={`tool-params-${record.name}`}
                                                rows={4}
                                                placeholder="输入JSON参数"
                                                defaultValue="{}"
                                            />
                                        </div>
                                    ),
                                    onOk: () => {
                                        const params = document.getElementById(`tool-params-${record.name}`).value;
                                        handleCallTool(record.name, params);
                                    }
                                });
                            }}
                        >
                            调用
                        </Button>
                    )
                }
            ];

            const resourceColumns = [
                {
                    title: '资源名称',
                    dataIndex: 'name',
                    key: 'name',
                    render: (text) => <Text strong>{text}</Text>
                },
                {
                    title: 'URI',
                    dataIndex: 'uri',
                    key: 'uri',
                    render: (text) => <Text code>{text}</Text>
                },
                {
                    title: '类型',
                    dataIndex: 'mimeType',
                    key: 'mimeType',
                    render: (text) => text ? <Tag>{text}</Tag> : '未知'
                }
            ];

            return (
                <Layout className="admin-container">
                    <Header className="header-bar">
                        <Title level={2} style={{ color: 'white', margin: 0 }}>
                            MCP Client 管理界面
                        </Title>
                    </Header>
                    
                    <Content className="content-area">
                        {/* 状态卡片 */}
                        <Card className="status-card">
                            <Row gutter={24}>
                                <Col span={6}>
                                    <Statistic 
                                        title="连接状态" 
                                        value={connectionStatus ? '已连接' : '未连接'}
                                        prefix={
                                            <div className={`status-dot ${connectionStatus ? 'connected' : ''}`}></div>
                                        }
                                    />
                                </Col>
                                <Col span={6}>
                                    <Statistic title="工具数量" value={tools.length} />
                                </Col>
                                <Col span={6}>
                                    <Statistic title="资源数量" value={resources.length} />
                                </Col>
                                <Col span={6}>
                                    <Statistic title="成功调用" value={statistics.successfulCalls} />
                                </Col>
                            </Row>
                        </Card>

                        {/* 操作按钮 */}
                        <Card className="action-buttons">
                            <Space size="large">
                                <Button 
                                    type="primary" 
                                    size="large"
                                    loading={loading}
                                    disabled={connectionStatus}
                                    onClick={handleConnect}
                                >
                                    连接服务器
                                </Button>
                                <Button 
                                    size="large"
                                    loading={loading}
                                    disabled={!connectionStatus}
                                    onClick={handleDisconnect}
                                >
                                    断开连接
                                </Button>
                                <Button 
                                    type="dashed" 
                                    size="large"
                                    onClick={() => {
                                        checkConnectionStatus();
                                        loadStatistics();
                                    }}
                                >
                                    刷新状态
                                </Button>
                                <Button 
                                    type="link" 
                                    size="large"
                                    onClick={() => window.open('/api-docs', '_blank')}
                                >
                                    API文档
                                </Button>
                            </Space>
                        </Card>

                        {/* 主要内容区域 */}
                        <Tabs defaultActiveKey="1" size="large">
                            <TabPane tab={`工具管理 (${tools.length})`} key="1">
                                <Card>
                                    <Table 
                                        columns={toolColumns}
                                        dataSource={tools}
                                        rowKey="name"
                                        pagination={{ pageSize: 10 }}
                                        loading={loading}
                                        locale={{ emptyText: connectionStatus ? '暂无工具' : '请先连接服务器' }}
                                    />
                                </Card>
                            </TabPane>
                            
                            <TabPane tab={`资源管理 (${resources.length})`} key="2">
                                <Card>
                                    <Table 
                                        columns={resourceColumns}
                                        dataSource={resources}
                                        rowKey="uri"
                                        pagination={{ pageSize: 10 }}
                                        loading={loading}
                                        locale={{ emptyText: connectionStatus ? '暂无资源' : '请先连接服务器' }}
                                    />
                                </Card>
                            </TabPane>
                            
                            <TabPane tab="服务器配置" key="3">
                                <Card>
                                    <Form layout="vertical">
                                        <Row gutter={24}>
                                            <Col span={12}>
                                                <Form.Item label="服务器URI">
                                                    <Input 
                                                        value={serverConfig.serverUri}
                                                        onChange={(e) => setServerConfig({...serverConfig, serverUri: e.target.value})}
                                                        placeholder="ws://localhost:8080/mcp"
                                                    />
                                                </Form.Item>
                                            </Col>
                                            <Col span={12}>
                                                <Form.Item label="服务器类型">
                                                    <Select 
                                                        value={serverConfig.type}
                                                        onChange={(type) => setServerConfig({...serverConfig, type})}
                                                        style={{ width: '100%' }}
                                                    >
                                                        <Select.Option value="neo4j">Neo4j</Select.Option>
                                                        <Select.Option value="postgresql">PostgreSQL</Select.Option>
                                                        <Select.Option value="filesystem">Filesystem</Select.Option>
                                                    </Select>
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                        
                                        <Form.Item label="服务器配置 (JSON)">
                                            <TextArea 
                                                className="json-editor"
                                                rows={8}
                                                value={JSON.stringify(serverConfig.config, null, 2)}
                                                onChange={(e) => {
                                                    try {
                                                        const config = JSON.parse(e.target.value);
                                                        setServerConfig({...serverConfig, config});
                                                    } catch (err) {
                                                        // 忽略JSON解析错误
                                                    }
                                                }}
                                            />
                                        </Form.Item>
                                    </Form>
                                </Card>
                            </TabPane>
                            
                            <TabPane tab="系统信息" key="4">
                                <Card>
                                    <Descriptions title="系统状态" bordered>
                                        <Descriptions.Item label="连接状态">
                                            <Badge 
                                                status={connectionStatus ? 'success' : 'error'} 
                                                text={connectionStatus ? '已连接' : '未连接'} 
                                            />
                                        </Descriptions.Item>
                                        <Descriptions.Item label="服务器URI">
                                            {serverConfig.serverUri}
                                        </Descriptions.Item>
                                        <Descriptions.Item label="服务器类型">
                                            <Tag color="blue">{serverConfig.type.toUpperCase()}</Tag>
                                        </Descriptions.Item>
                                        <Descriptions.Item label="工具数量">
                                            {tools.length}
                                        </Descriptions.Item>
                                        <Descriptions.Item label="资源数量">
                                            {resources.length}
                                        </Descriptions.Item>
                                        <Descriptions.Item label="客户端版本">
                                            1.0.0
                                        </Descriptions.Item>
                                    </Descriptions>
                                </Card>
                            </TabPane>
                        </Tabs>
                    </Content>
                </Layout>
            );
        };

        ReactDOM.render(<McpAdminPanel />, document.getElementById('root'));
    </script>
</body>
</html>